package com.zhengyisky.service;

import com.zhengyisky.mapper.UserMapper;
import com.zhengyisky.pojo.User;
import com.zhengyisky.utils.Result;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${jwt.privateKey}")
    private String privateKey;

    public Result checkLogin(User user) {
        User u = userMapper.findUserByUsername(user);
        if(u == null){
            return Result.error("账号不存在");
        }

        if(!passwordEncoder.matches(user.getPassword(), u.getPassword())){
            return Result.error("密码不正确");
        }

        //生成JWT令牌

        Map<String,Object> map = new HashMap();
        map.put("id", u.getId());
        map.put("username",u.getUsername());
        map.put("dept",u.getDeptId());

        String jwt = Jwts.builder().signWith(SignatureAlgorithm.HS256, privateKey).setClaims(map).compact();
        stringRedisTemplate.opsForValue().set("user:token:"+u.getId(), jwt, 10, TimeUnit.MINUTES);
        return Result.success(jwt);
    }
}
